import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import BaseSwiper from 'swiper';
import 'swiper/dist/css/swiper.css';
import './index.scss';

class Swiper extends React.Component {
    render() {
        let { navigation, slide } = this.props;
        let className = `swiper-container ${this.props.className}`
        if (slide.length > 0) {
            return (
                <div className={className} style={this.props.style}>
                    <div className="swiper-wrapper">
                        {
                            slide.map((i, index) => {
                                return (
                                    <div key={index} className="swiper-slide">
                                        <img src={i} alt="" />
                                    </div>
                                )
                            })
                        }

                    </div>
                    {/* <!-- 如果需要导航按钮 --> */}
                    {
                        navigation && (
                            <Fragment>
                                <div className="swiper-button-prev"></div>
                                <div className="swiper-button-next"></div>
                            </Fragment>
                        )
                    }
                </div>
            )
        } else {
            return null;
        }
    }

    initSwiper() {
        this.mySiwper = new BaseSwiper('.swiper-container', {
            autoplay: this.props.autoplay,
            navigation: this.props.navigation ? {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            } : {},
        })
    }
    componentDidUpdate() {
        if (this.mySiwper) {
            this.mySiwper.destroy();
        }
        this.initSwiper();
    }
}

Swiper.propTypes = {
    navigation: PropTypes.bool, // 上下页
    autoplay: PropTypes.bool,
    slide: PropTypes.arrayOf(PropTypes.string).isRequired, // ['']
}

Swiper.defaultProps = {
    navigation: false,
    autoplay: false
}
export default Swiper;
